package com.zxy.leetcode.lcci;

import com.zxy.leetcode.common.ListNode;
import com.zxy.leetcode.common.ListNodeHelper;

import java.util.HashSet;
import java.util.Set;

/**
 * https://leetcode-cn.com/problems/remove-duplicate-node-lcci/
 *
 * 移除重复节点
 * 编写代码，移除未排序链表中的重复节点。保留最开始出现的节点。
 */
public class Test0201 {

    public static void main(String[] args) {
        Test0201 test = new Test0201();
        int[] nums = {1, 2, 3, 3, 2, 1};
        ListNode head = ListNodeHelper.build(nums);
        ListNodeHelper.print(head);
        head = test.removeDuplicateNodes(head);
        ListNodeHelper.print(head);
    }

    public ListNode removeDuplicateNodes(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        Set<Integer> set = new HashSet<>();
        set.add(head.val);
        ListNode pre = head;
        ListNode cur = pre.next;

        while (cur != null) {
            if (set.contains(cur.val)) {
                pre.next = cur.next;
                cur = cur.next;
            }else {
                set.add(cur.val);
                pre = cur;
                cur = cur.next;
            }
        }

        return head;
    }
}
